package com.mh.controller;

import com.mh.dto.vo.R;
import com.mh.service.AiRecorderService;
import com.mh.service.FireflyService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * 记账接口：接收前端文本，调用AI解析后同步到Firefly
 * 
 * @author zmh
 */
@RestController
@RequestMapping("/api/bookkeeping")
@RequiredArgsConstructor
@Slf4j
public class BookkeepingController {
    private final AiRecorderService aiRecorderService;
    private final FireflyService fireflyService;

    /**
     * 提交记账文本，AI解析后同步到Firefly
     * @param request 前端请求体（包含text字段）
     * @return 处理结果
     */
    @PostMapping("/submit")
    public Mono<R<Map<String, Object>>> submitBookkeepingText(@RequestBody Map<String, String> request) {
        // 参数验证
        if (request == null) {
            log.warn("记账请求参数为空");
            return Mono.just(R.error("请求参数不能为空"));
        }
        
        String text = request.get("text");
        if (text == null || text.trim().isEmpty()) {
            log.warn("记账文本内容为空");
            return Mono.just(R.error("文本内容不能为空"));
        }
        
        log.info("收到记账请求，文本: {}", text);
        
        // 1. 调用AI解析文本
        return aiRecorderService.parseBookkeepingText(text)
                // 2. 将解析结果同步到Firefly III
                .flatMap(aiResult -> {
                    log.info("AI解析成功，结果: {}", aiResult);
                    return fireflyService.createTransaction(aiResult)
                            // 3. 返回处理结果
                            .map(fireflyResult -> {
                                Map<String, Object> data = new HashMap<>();
                                data.put("ai_result", aiResult);
                                data.put("firefly_result", fireflyResult);
                                log.info("记账同步到Firefly成功");
                                return R.success(data);
                            });
                })
                // 错误处理
                .onErrorResume(e -> {
                    log.error("记账处理失败: {}", e.getMessage(), e);
                    return Mono.just(R.error("处理失败: " + e.getMessage()));
                });
    }
}